package main

import (
	"fmt"
	"github.com/gorilla/sessions"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"net/http"
)

// Session 中间件促进了 gorilla/sessions 支持的 HTTP 会话管理。默认提供了基于 cookie 与文件系统的会话存储；
// 然而，你也可以访问 community maintained implementation 来参考其各式各样的后端实现。

var sessionKey []byte = []byte("secret")

func main() {
	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.RequestID())
	//用法一
	//e.Use(session.Middleware(sessions.NewCookieStore(sessionKey)))

	//用法二：
	e.Use(session.MiddlewareWithConfig(CustomSessionConfig()))
	e.GET("/session/w", WriteSession)
	e.GET("/session/r", ReadSession)
	e.GET("/session/d", DeleteSession)
	e.Start(":80")

}
func WriteSession(c echo.Context) error {
	sess, err := session.Get("session", c)
	if err != nil {
		return err
	}
	sess.Options = &sessions.Options{
		Path:     "/",
		MaxAge:   86400 * 7,
		HttpOnly: true,
	}
	sess.Values["foo"] = "bar"
	err = sess.Save(c.Request(), c.Response())
	if err != nil {
		return err
	}
	return c.String(200, "ok")
}

func ReadSession(c echo.Context) error {
	sess, err := session.Get("session", c)
	if err != nil {
		return err
	}
	return c.String(http.StatusOK, fmt.Sprintf("foo=%v\n", sess.Values["foo"]))
}

func DeleteSession(c echo.Context) error {
	sess, err := session.Get("session", c)
	if err != nil {
		return err
	}
	sess.Options = &sessions.Options{
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
	}
	err = sess.Save(c.Request(), c.Response())
	return c.String(http.StatusOK, "Session deleted")
}

func CustomSessionConfig() session.Config {
	return session.Config{
		Skipper: middleware.DefaultSkipper,
		Store:   sessions.NewCookieStore(sessionKey),
	}
}
